package com.example.article.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.article.core.page.response.APIResponse;
import com.example.article.core.page.response.PageableResponse;
import com.example.article.dto.response.UserResponse;
import com.example.article.entity.User;
import com.example.article.service.impl.UserServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author zhaung
 * @since 2022-04-18
 */
@RestController
@RequestMapping("/user")
@Api(tags = "用户管理")
@Slf4j
@RequiredArgsConstructor
public class UserController {
    private final UserServiceImpl userService;

    private final BCryptPasswordEncoder encoder;

    @GetMapping("/selUserById")
    @ApiOperation("通过id查询用户")
    public APIResponse<UserResponse> selUserById(@RequestParam("id") String id) {
        User user = userService.selUserById(Long.parseLong(id));
        return APIResponse.makeSuccess(
                UserResponse.builder()
                        .id(String.valueOf(user.getId()))
                        .createdTime(user.getCreatedTime())
                        .updatedTime(user.getUpdatedTime())
                        .username(user.getUsername())
                        .build());
    }

    @DeleteMapping("/delUserById")
    @ApiOperation("通过id删除用户")
    public APIResponse<?> delUserById(@RequestParam("id") String id) {
        User user = new User();
        user.setId(Long.parseLong(id));
        if (userService.updateById(user)) {
            return APIResponse.makeMessage("删除成功");
        } else {
            return APIResponse.makeMessage("删除失败");
        }
    }

    @PostMapping("/selUser")
    @ApiOperation("查询用户信息")
    public PageableResponse selList() {

        QueryWrapper<User> wrapper = new QueryWrapper<User>();
        wrapper.lambda()
                .isNull(User::getDeletedTime);
        List<User> collect = userService
                .list(wrapper).stream()
                .limit(10)
                .collect(Collectors.toList());
        if (collect.isEmpty()) {
            return PageableResponse.builder()
                    .Items(null)
                    .build();
        }
        List<UserResponse> responseList = collect.stream().map(temp -> {
            return UserResponse.builder()
                    .id(String.valueOf(temp.getId()))
                    .username(temp.getUsername())
                    .createdTime(temp.getCreatedTime())
                    .updatedTime(temp.getUpdatedTime())
                    .build();
        }).collect(Collectors.toList());
        return PageableResponse.<List<User>>builder()
                .pageNo(Integer.toUnsignedLong(2))
                .pageSize(Integer.toUnsignedLong(2))
                .totalItems(Integer.toUnsignedLong(collect.size()))
                .totalPages(Integer.toUnsignedLong((int) Math.ceil((double) collect.size() / 2)))   //向上取整
                .Items(responseList)
                .build();
    }

    @PostMapping(value = "/insUser", produces = "application/json;charset=UTF-8")
    @ApiOperation("添加用户信息")
    public APIResponse<?> insList(@RequestBody @ApiParam("JSON参数") User user) {
        List<User> userList = userService.list();
        for (User temp : userList) {
            log.info(temp.getUsername());
            if (temp.getUsername().equals(user.getUsername())) {
                return APIResponse.makeMessage("用户已经存在");
            }
        }
        user.setPassword(encoder.encode(user.getPassword()));
        log.info(String.valueOf(user));
        if (userService.save(user)) {
            return APIResponse.makeMessage("添加成功");
        } else {
            return APIResponse.makeMessage("添加失败");
        }
    }

}
